package com.itheima.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.ClazzException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageBean;
import com.itheima.service.ClazzService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Resource
    private ClazzMapper clazzMapper;

    @Override
    public PageBean<Clazz> pageQuery(String name, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        //开启分页
        PageHelper.startPage(page,pageSize);
        //查询列表：不需要传参起始索引与查询数量
        Page<Clazz> clazzPage = clazzMapper.page(name,begin,end);
        //封装结果
//        Page<Emp> p = (Page<Emp>) empPage;
        for (Clazz clazz : clazzPage) {
            if (LocalDate.now().isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开课");
            }else if (LocalDate.now().isAfter(clazz.getEndDate())){
                clazz.setStatus("已结课");
            }else {
                clazz.setStatus("在读");
            }
        }

        return new PageBean<>((int) clazzPage.getTotal(),clazzPage);
    }

    /**
     * 新增班级
     */
    @Override
    public void addClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insetClazz(clazz);
    }

    /**
     * 根据ID查询班级接口
     */
    @Override
    public Clazz selectById(Integer id) {
        Clazz clazz = clazzMapper.selectById(id);
        return clazz;
    }

    /**
     * 修改班级
     */
    @Override
    public void putClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }

    /**
     * 删除班级
     */
    @Override
    public void deleteById(Integer id) {
        Clazz clazz = clazzMapper.selectByStuId(id);
        if (clazz != null) {
            throw new ClazzException("当前班级下有学生，不能直接删除！");
        }
        clazzMapper.deleteById(id);
    }

    /**
     * 查询所有班级
     */
    @Override
    public List<Clazz> getAllClazz() {
        List<Clazz> lists = clazzMapper.selectAllClazz();
        return lists;
    }
}
